<template>
  <div class="prepare">
    <div class="bg-orange">
      <van-cell-group
        class="express"
        :border="false"
      >
        <van-cell
          @click="showAddress = true"
          v-if="chosenAddressId>0"
        >
          <div class="van-cell-title">
            <span class="van-cell-text">{{currentContact.name}}</span>
            <span class="van-cell-text">{{currentContact.tel}}</span>
            <van-tag
              plain
              mark
              v-if="currentContact.isDefault"
            >{{currentContact.tag}}</van-tag>
          </div>
          <div class="van-cell-detail van-ellipsis">{{currentContact.address}}</div>
          <van-icon
            slot="right-icon"
            name="arrow"
            class="van-cell__right-icon"
          />
        </van-cell>
        <van-cell
          :to="{name:'user/address/add'}"
          v-else
        >
          <div class="van-cell-title">
            <span class="van-cell-text">收件人</span>
            <span class="van-cell-text"></span>
          </div>
          <div class="van-cell-detail van-ellipsis">您还没有设置收件地址，请先添加后再使用</div>
          <van-icon
            slot="right-icon"
            name="arrow"
            class="van-cell__right-icon"
          />
        </van-cell>
      </van-cell-group>

      <van-cell-group
        class="order-resume"
        :border="false"
        v-show="list.length"
      >
        <van-card
          :title="list[0].name"
          :desc="list[0].sku"
          :num="list[0].num"
          :price="list[0].price"
          :thumb="list[0].thumb"
          v-if="list.length==1"
        />
        <van-cell
          :value="unitNumber()"
          v-else-if="list.length>1"
          is-link
        >
          <template slot="title">
            <span
              v-for="goods in list.slice(0,3)"
              :key="goods.id"
            >
              <van-image :src="goods.thumb" />
            </span>
          </template>
        </van-cell>
      </van-cell-group>
      <van-cell-group>
        <van-cell title="商品总价">
          <div class="price-cny font-black">{{order.amount}}</div>
        </van-cell>
        <van-cell title="运费">
          <div class="price-cny font-black">{{order.express}}</div>
        </van-cell>
        <van-cell
          title="活动优惠"
          v-if="order.discount"
        >
          <div class="price-cny font-black">{{order.discount}}</div>
        </van-cell>
        <van-cell
          title="优惠券"
          value="无可用"
          is-link
        />
        <van-cell
          title="礼品卡"
          value="无可用"
          is-link
        />
        <van-cell title="小计">
          <div class="price-cny">{{order.subtotal+order.express}}</div>
        </van-cell>
      </van-cell-group>
    </div>

    <van-cell-group class="mt10">
      <van-cell
        title="发票"
        value="电子发票-个人"
        is-link
      />
    </van-cell-group>

    <!-- 联系人列表 -->
    <van-popup
      v-model="showAddress"
      position="bottom"
    >
      <van-address-list
        v-model="chosenAddressId"
        :list="address.list"
        add-button-text="+ 新增收货地址"
        @add="onAdd"
        @edit="onEdit"
        @select="onSelect"
      />
    </van-popup>

    <!-- 支付弹窗 -->
    <payment-dialog
      v-model="showPayment"
      :order-id="orderId"
    ></payment-dialog>

    <van-submit-bar
      :price="orderPaymentPirce"
      button-text="去付款"
      :label="`共${list.length}件，应付金额：`"
      @submit="onSubmit"
    >
      <span slot="tip">
        如未在订单过期前付款,系统将会自动取消订单
      </span>
    </van-submit-bar>
  </div>
</template>

<script>
import {
  Tag,
  Col,
  Icon,
  Toast,
  Cell,
  CellGroup,
  Card,
  Button,
  Panel,
  Image,
  Popup,
  AddressList,
  NoticeBar,
  SubmitBar
} from 'vant'
import PaymentDialog from '@/components/paymentDialog'

export default {
  components: {
    PaymentDialog,
    [Tag.name]: Tag,
    [Col.name]: Col,
    [Icon.name]: Icon,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Panel.name]: Panel,
    [Card.name]: Card,
    [Button.name]: Button,
    [Image.name]: Image,
    [Popup.name]: Popup,
    [AddressList.name]: AddressList,
    [NoticeBar.name]: NoticeBar,
    [SubmitBar.name]: SubmitBar
  },
  data () {
    return {
      test: false,
      chosenAddressId: 0,
      showSubmiting: false,
      disableSubmit: false,
      orderId: 0,
      showAddress: false,
      showPayment: false,
      address: {
        list: []
      },
      order: {
        amount: 0,
        discount: 0,
        subtotal: 0,
        express: '--'
      },
      list: []
    }
  },
  created () {
    this.onLoad()
  },
  computed: {
    orderPaymentPirce () {
      return (this.order.subtotal + this.order.express) * 100
    },
    currentContact () {
      let id = this.chosenAddressId
      let data = this.address.list.filter(item => item.id === id)[0]
      console.log(data)
      return data
    }
  },
  beforeRouteUpdate (to, from, next) {
    // 在当前路由改变，但是该组件被复用时调用
    // 对于一个带有动态参数的路径 /good/:id，在 /good/1 和 /good/2 之间跳转的时候，
    // 由于会渲染同样的good组件，因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
    console.log('****************Test1*******Update***********')
    console.log(this, 'Update') // 当前组件实例
    console.log('to', to)
    console.log('from', from)
    console.log('next', next)
    next()
  },
  beforeRouteLeave (to, from, next) {
    console.group('beforeRouteLeave')
    next(false)
    if (to.name === 'cart' && this.orderId !== 0) {
      next({
        name: 'order/view/:id',
        params: {
          id: this.orderId
        },
        replace: true
      })
    } else {
      next()
    }
    console.groupEnd('beforeRouteLeave')
  },
  watch: {
    showPayment (curVal, oldVal) {
      if (curVal === false && oldVal === true) {
        console.log('当前值：', curVal)
        console.log('当前订单ID：', this.orderId)
        this.gotoOrder(this.orderId)
        console.log('已跳转地址', 'order/view/' + this.orderId)
      }
    },
    chosenAddressId: {
      handler (curVal, oldVal) {
        if (curVal !== oldVal) {
          this.reckonExpress(curVal)
        }
      },
      deep: true
    }
  },
  methods: {
    gotoOrder (id) {
      if (id !== 0) {
        this.$router.replace({
          name: 'order/view/:id',
          params: {
            id: id
          }
        })
      }
    },
    onLoad () {
      this.$http.shop.getPackBalance().then(res => {
        let data = res.data
        if (data && data.list.length) {
          this.list = data.list
          this.order = data.order
          this.address = data.address
          this.chosenAddressId = data.chosenAddressId
        } else {
          this.$router.replace({ name: 'cart' })
        }
      })
    },
    onSubmit () {
      if (this.orderId === 0) {
        this.disableSubmit = true
        this.$http.shop
          .createOrder({
            address_id: this.chosenAddressId,
            carts: this.getCartIds(),
            coupons: this.getCoupons()
          })
          .then(response => {
            let order = response.data
            console.log('[order]', order)
            if (order) {
              this.orderId = order.order_id
              this.showPaymentControl()
            } else {
              Toast('订单创建失败，请重试~')
            }
            this.disableSubmit = false
          })
          .catch(error => {
            this.disableSubmit = false
            console.log(error)
            Toast(error.data.message)
          })
      } else {
        this.showSubmiting = true
        console.log('直接调用支付弹框')
        this.showPaymentControl()
      }
    },

    showPaymentControl () {
      console.log('调用支付弹框，支付订单ID：' + this.orderId)
      this.showPayment = true
    },

    formatPrice () {
      return this.order.price
    },

    getCoupons () {
      let discounts = [1, 2, 3]
      return discounts // .join(',')
    },

    getCartIds () {
      // 缓存数组长度，进一步提升代码性能
      let len = this.list.length
      let result = []

      for (let i = 0; i < len; i++) {
        result[i] = this.list[i]['id']
      }
      return result
    },

    unitNumber () {
      return '共' + this.list.length + '件'
    },

    // 添加联系人
    onAdd (item) {
      console.log(item)
      this.$router.push({
        name: 'user/address/add'
      })
    },

    // 编辑联系人
    onEdit (item) {
      this.$router.push({
        name: 'user/address/:id',
        params: {
          id: item.id
        }
      })
    },

    // 选中联系人
    onSelect () {
      this.showAddress = false
    },

    // 添加联系人
    reckonExpress (id) {
      if (this.chosenAddressId !== 0) {
        // 缓存数组长度，进一步提升代码性能
        let len = this.list.length
        let result = []
        for (let i = 0; i < len; i++) {
          let item = this.list[i]
          let person = {
            product_id: item.product_id,
            num: item.num
          }
          result.push(person)
        }
        let params = {
          areacode: this.currentContact.areaCode,
          items: result
        }
        console.log(params)
        this.$http.shop.reckonOrderExpress(params).then(response => {
          this.order.express = response.data
        })
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.express.van-cell-group {
  padding-top: 10px;
  background: transparent;
  .van-cell {
    background: transparent;
    color: #fff;
    .van-tag {
      background: transparent;
      color: rgba(255, 255, 255, 0.8);
      padding: 2px 8px;
      &::after {
        border-radius: 20px;
      }
    }
    &-text {
      font-size: 18px;
      font-weight: 500;
      color: rgba(255, 255, 255, 0.9);
    }
    &-detail {
      font-size: 14px;
      color: rgba(255, 255, 255, 0.8);
    }
    &__right-icon {
      align-self: center;
      color: #fff;
    }
  }
}

.order-resume {
  margin-top: 10px;
  border-radius: 10px 10px 0 0;
  > * {
    border-radius: 10px 10px 0 0;
    padding: 10px 15px;
  }
  /deep/ .van-card {
    &__thumb {
      margin-right: 15px;
    }
    &__title {
      min-height: 40px;
      line-height: 20px;
      font-size: 14px;
    }
  }
  /deep/ .van-cell {
    height: 80px;
    padding-left: 0;
    > * {
      align-self: center;
    }
    .van-cell__title {
      flex: auto;
      -webkit-box-flex: auto;
      -ms-flex: auto;
      span {
        width: 60px;
        height: 60px;
        display: inline-block;
        margin-left: 10px;
        img {
          width: 100%;
          height: 100%;
          border-radius: 5px;
          outline-width: 0px;
          vertical-align: top;
        }
      }
    }
  }
}
.van-submit-bar__text {
  text-align: left;
}
</style>
